<template>
  <div class="edit-address-container">
    <!-- 头部导航，支持返回 -->
    <header class="page-header">
      <span class="back" @click="goBack">＜</span>
      <h1 class="title">编辑收货地址</h1>
    </header>

    <form class="address-form">
      <!-- 联系人 -->
      <div class="form-item">
        <label class="label">联系人</label>
        <van-field
          v-model="form.name"
          type="text"
          placeholder="收货人姓名"
          required
          :rules="[{ required: true, message: '请输入联系人姓名' }]"
        />
      </div>

      <!-- 手机号 -->
      <div class="form-item">
        <label class="label">手机号</label>
        <van-field
          v-model="form.phone"
          type="tel"
          placeholder="收货人手机号码"
          required
          :rules="[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
        />
      </div>

      <!-- 省市区选择 -->
      <div class="form-item">
        <label class="label">省市区</label>
        <van-field
          v-model="selectedAreaText"
          readonly
          clickable
          placeholder="点击选择省市区"
          @click="showArea = true"
          class="area-field"
          :class="{ 'has-selected': selectedAreaText }"
        />
        <van-popup
          v-model:show="showArea"
          position="bottom"
          :style="{ height: '70%' }"
          class="area-popup"
        >
          <van-area
            :area-list="areaList"
            @confirm="onConfirm"
            @cancel="showArea = false"
            class="area-component"
            :columns-placeholder="['请选择省', '请选择市', '请选择区']"
            :value="initAreaValues" 
          />
        </van-popup>
      </div>

      <!-- 详细地址 -->
      <div class="form-item">
        <label class="label">详细地址</label>
        <van-field
          v-model="form.detailAddress"
          type="text"
          placeholder="楼号、门牌等"
          required
          :rules="[{ required: true, message: '请输入详细地址' }]"
        />
      </div>

      <!-- 设为默认 -->
      <div class="form-item default-checkbox">
        <label class="label">设为默认</label>
        <van-switch v-model="form.isDefault" size="24px" />
      </div>

      <!-- 提交按钮 -->
      <van-button
        type="primary"
        class="submit-btn"
        @click="handleSubmit"
        :loading="submitting"
      >
        提交
      </van-button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { areaList } from '@vant/area-data'
import api from '@/api/history' 
import { useRouter, useRoute } from 'vue-router'
// 补充导入这两个方法
import { showSuccessToast, showFailToast } from 'vant'; 

const router = useRouter()
const route = useRoute()

// 表单数据
const form = ref({
  id: '', // 地址 ID，用于接口更新
  name: '',
  phone: '',
  region: { codes: [], names: [] }, // 省市区编码和名称
  detailAddress: '',
  isDefault: false
})

// 省市区选择相关
const showArea = ref(false)
const selectedAreaText = ref('')
const initAreaValues = ref([]) // 用于回显已选省市区
const submitting = ref(false) // 提交加载状态

// 页面加载时初始化数据
onMounted(() => {
  // 从路由参数中获取地址 ID
  const addressId = route.params.addressId
  if (addressId) {
    // 调用后端接口，根据地址 ID 获取地址详情
    api.get(`/address/${addressId}`).then((response) => {
      const address = response.data
      form.value = {
        ...address,
        id: addressId // 记录地址 ID
      }
      // 初始化省市区回显
      selectedAreaText.value = address.region.names.join('')
      initAreaValues.value = address.region.codes.map((code) => ({ value: code }))
    }).catch((error) => {
      console.error('获取地址详情失败:', error)
      showFailToast('获取地址详情失败，请重试')
    })
  }
})

// 地址选择确认处理
const onConfirm = (result) => {
  try {
    const selectedOptions = result.selectedOptions || result.options || result || []
    if (selectedOptions.length < 3) {
      throw new Error('请选择完整的省市区')
    }
    const [province, city, district] = selectedOptions
    let displayText = ''
    // 特殊处理港澳台等地区
    if (['710000', '810000', '820000'].includes(province.value)) {
      displayText = `${province.text}${district.text}`
    } else if (['110000', '310000', '120000', '500000'].includes(province.value)) {
      displayText = `${province.text}${district.text}`
    } else {
      displayText = `${province.text}${city.text}${district.text}`
    }
    selectedAreaText.value = displayText
    form.value.region = {
      codes: selectedOptions.map((opt) => opt.value),
      names: [province.text, city.text, district.text]
    }
    showArea.value = false
  } catch (error) {
    console.error('地区选择处理失败:', error)
    showFailToast(error.message || '地区选择失败，请重试')
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 表单校验（使用 Vant Field 的校验规则，也可自定义）
const validateForm = () => {
  // 遍历所有 Field 触发校验
  const fields = document.querySelectorAll('.van-field')
  let is_valid = true
  fields.forEach((field) => {
    const input = field.querySelector('input')
    if (input && input.validity && !input.validity.valid) {
      is_valid = false
      // 手动触发错误提示
      field.dispatchEvent(new Event('blur'))
    }
  })
  return is_valid
}

// 提交编辑
const handleSubmit = async () => {
  if (!validateForm()) return
  if (!selectedAreaText.value) {
    showFailToast('请选择省市区')
    return
  }

  submitting.value = true
  try {
    const fullAddress = `${selectedAreaText.value}${form.value.detailAddress}`
    // 调用后端编辑地址接口：PUT /address/{address_id}  这里你之前用的post，和后端接口定义的put不符，记得改成put
    const res = await api.post(`/address/${form.value.id}`, { 
      name: form.value.name,
      phone: form.value.phone,
      address: fullAddress,
      is_default: form.value.isDefault,
      regionCodes: form.value.region.codes,
      regionNames: form.value.region.names
    })
    showSuccessToast('地址编辑成功')
    setTimeout(() => {
      goBack()
    }, 500)
  } catch (err) {
    console.error('编辑地址失败:', err)
    const response = err.response
    const isUnauthorized =
      (response && response.status === 401) ||
      (response && response.data && response.data.code === 401)

    if (isUnauthorized) {
      localStorage.removeItem('token')
      showFailToast('登录已过期，请重新登录')
      setTimeout(() => {
        router.push('/login')
      }, 500)
    } else {
      showFailToast('地址编辑失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.edit-address-container {
  padding: 15px;
  max-width: 600px;
  margin: 0 auto;
  background-color: #fff;
}
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.back {
  font-size: 24px;
  cursor: pointer;
  margin-right: 10px;
  color: #333;
}
.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.form-item {
  margin-bottom: 15px;
}
.label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}
.area-field {
  width: 100%;
}
.area-field.has-selected .van-field__value {
  color: #333 !important;
  font-weight: 500;
}
.van-field__value {
  text-align: left !important;
}
.area-popup {
  z-index: 2001;
}
.van-overlay {
  z-index: 2000;
}
.area-component {
  height: 100%;
}
.default-checkbox {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}
.submit-btn {
  width: 100%;
  margin-top: 10px;
}
</style>